<route lang="json5">
{
  layout: 'noTabBar',
  style: {
    navigationBarTitleText: '选择小区',
  },
}
</route>

<template>
  <view class="select-community-container p-4">
    <view class="text-lg font-bold mb-4">请选择要进入的小区</view>

    <view class="community-list">
      <view
        v-for="community in communities"
        :key="community.id"
        class="community-item bg-white rounded-lg p-4 mb-3 flex items-center justify-between"
        @click="handleSelect(community)"
      >
        <view class="community-info">
          <view class="community-name text-base font-medium">{{ community.community.name }}</view>
          <view class="community-address text-sm text-gray-500 mt-1">
            {{ community.community.address }}
            角色：{{ roleMap[community.role] }}
          </view>
        </view>
        <wd-icon name="arrow-right" />
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useUserStore } from '@/store'
import { components } from '@/types/ApiInterface'

const roleMap = {
  SUPER_ADMIN: '超级管理员',
  ADMIN: '小区管理员',
  PMC_WORKER: '物业工作人员',
  USER: '用户',
  GUEST: '访客',
}

const userStore = useUserStore()
const communities = ref<components['schemas']['CommunityUserStatus'][]>([])

onMounted(() => {
  // 从用户store中获取communities
  const userInfo = userStore.userInfo
  if (userInfo?.communities) {
    communities.value = userInfo.communities
  } else {
    // 如果没有communities数据，返回登录页
    uni.showToast({
      title: '获取小区信息失败',
      icon: 'none',
    })
    setTimeout(() => {
      uni.redirectTo({
        url: '/pages/login/index',
      })
    }, 1500)
  }
})

const handleSelect = (community: components['schemas']['CommunityUserStatus']) => {
  // 将选中的小区信息保存到store
  userStore.setCurrentCommunity(community)

  // 跳转到首页
  uni.reLaunch({
    url: '/pages/index/index',
  })
}
</script>

<style lang="scss" scoped>
.select-community-container {
  min-height: 100vh;
  background-color: #f8f8f8;
}

.community-item {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);

  &:active {
    opacity: 0.8;
  }
}
</style>
